package cn.wolfcode.wolf2w.redis.impl;

import cn.wolfcode.wolf2w.domain.Strategy;
import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.redis.IStrategyStatisVORedisService;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import cn.wolfcode.wolf2w.redis.vo.StrategyStatisVO;
import cn.wolfcode.wolf2w.util.Consts;
import cn.wolfcode.wolf2w.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


@Service
public class UserInfoRedisService implements IUserInfoRedisService {

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private IStrategyStatisVORedisService strategyStatisVORedisService;

    @Value("${sms.url}")
    private String url;

    @Value("${sms.appkey}")
    private String appkey;


    @Override
    public void sendVerifyCode(String phone) {

        String code = UUID.randomUUID().toString().replace("-", "").substring(0, 4);

        System.out.println(code);

        StringBuilder builder = new StringBuilder();

        builder.append("【创信】您的验证码为:").append(code).append("有效期为:").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟");

        System.out.println("发送验证码");

        //RestTemplate:spring 封装用于发起http请求的工具类
        RestTemplate rest = new RestTemplate();
        //参数1: 请求url,
        //参数2: 响应结果的数据类型
        //参数3: 请求携带的参数

        //String url = "https://way.jd.com/chuangxin/dxjk?mobile={1}&content={2}&appkey={3}";

        //String appkey = "f57351a0ee0a050c64c90e113630541e";

        String ret = rest.getForObject(url, String.class, phone, builder, appkey);

        System.out.println(ret);

        //if (!ret.contains("Success")){
        //    throw new LogicException("短信发送失败");
        //}

        String str = RedisKeys.VERIFY_CODE.join(phone);

        template.opsForValue().set(str, code, Consts.VERIFY_CODE_VAI_TIME, TimeUnit.MINUTES);
    }

    @Override
    public String getVerifyCode(String phone) {

        String str = RedisKeys.VERIFY_CODE.join(phone);

        String code = template.opsForValue().get(str);

        return code;
    }

    @Override
    public String token(UserInfo user) {

        String str = UUID.randomUUID().toString().replace("-","" );

        String token = RedisKeys.USER_TOKEN.join(str);

        template.opsForValue().set(token, JSON.toJSONString(user), Consts.USER_INFO_TOKEN_VAI_TIME * 60L, TimeUnit.SECONDS);

        return str;
    }

    @Override
    public UserInfo getUserInfoByToken(String token) {

        if (!StringUtils.hasLength(token)){

            return null;
        }

        String key = RedisKeys.USER_TOKEN.join(token);

        if (template.hasKey(key)){

            String str = template.opsForValue().get(key);

            if (StringUtils.hasLength(str)){

                UserInfo userInfo = JSON.parseObject(str, UserInfo.class);

                return userInfo;
            }
        }

        return null;
    }

    public boolean queryStrategyFavor(String sid, UserInfo userInfo) {

        String join = RedisKeys.USER_FAVOR_VO.join(userInfo.getId());


        List<String> userList = new ArrayList<>();
        if (template.hasKey(join)){

            String str = template.opsForValue().get(join);

            userList = JSON.parseArray(str, String.class);
        }

        StrategyStatisVO vo = strategyStatisVORedisService.statisVo(sid);

        if (userList.contains(sid)){

            vo.setFavornum(vo.getFavornum() - 1);

            userList.remove(sid);
        }else {

            vo.setFavornum(vo.getFavornum() + 1);

            userList.add(sid);
        }

        template.opsForValue().set(join, JSON.toJSONString(userList));
        strategyStatisVORedisService.setStrategyStatisVO(vo);
        return userList.contains(sid);
    }

    @Override
    public List<String> queryStrategyFavorId(String userId) {

        if (!StringUtils.hasLength(userId)){
            return Collections.EMPTY_LIST;
        }


        String join = RedisKeys.USER_FAVOR_VO.join(userId);

        List<String> list = new ArrayList<>();
        if (template.hasKey(join)){

            String str = template.opsForValue().get(join);

            list = JSON.parseArray(str, String.class);

        }
        return list;
    }
}
